package com.chainyoung.trademarket.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.component_tmtrade.bean.FiatOrder;
import com.chainyoung.component_tmtrade.constant.StringConstant;
import com.chainyoung.component_tmtrade.ui.adapter.TradeAgencyAdapter;
import com.chainyoung.component_tmtrade.ui.adapter.TradeFiatCurrencyOrderAdapter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.chainyoung.trademarket.R;
import com.chainyoung.trademarket.adapter.MessageListAdapter;
import com.chainyoung.trademarket.di.component.DaggerMainComponent;
import com.chainyoung.trademarket.di.component.DaggerMainFragmentComponent;
import com.chainyoung.trademarket.di.module.MainFragmentModule;
import com.chainyoung.trademarket.di.module.MainModule;
import com.chainyoung.trademarket.entity.Msg;
import com.chainyoung.trademarket.entity.MsgNum;
import com.chainyoung.trademarket.mvp.contract.MsgFragmentContract;
import com.chainyoung.trademarket.mvp.presenter.MsgFragmentPresenter;
import com.chainyoung.trademarket.ui.ChatRoomActivity;
import com.chainyoung.trademarket.ui.MessageDetailActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.chainyoung.common.constant.CommonStringConstants.URL;
import static com.chainyoung.common.event.BaseEvent.EventCode.MSG_NUM;


public class MessageFragment extends BaseFragment<MsgFragmentPresenter> implements MsgFragmentContract.View {

    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;


    public final static String ADMIN_MSG = "admin";
    public final static String ORDER_MSG = "order";
    public final static String CHAT_MSG = "chat";


    private String msgType;
    private MessageListAdapter mAdapter;

    private List<Msg> mData = new ArrayList<>();
    private boolean isCanloadMore;
    private int pageNo = 1;
    private boolean isFirst = true;
    private int removedPosition;
    private int changedPosition;
    private Msg msg;
    private boolean isDel;

    public static MessageFragment newInstance(String msgType) {
        final MessageFragment fragment = new MessageFragment();
        final Bundle args = new Bundle();
        args.putString("msgType", msgType);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            msgType = getArguments().getString("msgType");
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMainFragmentComponent.builder()
                .appComponent(appComponent)
                .mainFragmentModule(new MainFragmentModule(this))
                .build()
                .inject(this);

    }

    @Override
    protected boolean useLoadSir() {
        return true;
    }

    @Override
    protected void onPageRetry(View v) {
        super.onPageRetry(v);
        refreshData();
    }

    public void refreshData() {
        showPageLoading();
        pageNo = 1;
        getData();
    }

    @Override
    protected void initUi() {
        super.initUi();
        mAdapter = new MessageListAdapter(mData, msgType);
        rvList.setAdapter(mAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, com.chainyoung.component_tmtrade.R.drawable.shape_divider_gray));
        rvList.addItemDecoration(itemDecoration);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    getData();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                getData();
            }
        });

        mAdapter.setOnClickCancel(new MessageListAdapter.OnClickCancel() {
            @Override
            public void onDelMsg(int position, String id) {
                removedPosition = position;
                updateMsg(position, id, true);
            }

            @Override
            public void onUpdateStatus(int position, String id, Msg item) {
                msg = item;
                changedPosition = position;
                if (item.isIs_read()) {
                    gotoOtherActivity();
                } else {
                    updateMsg(position, id, false);
                }
            }
        });
    }

    private void updateMsg(int position, String id, Boolean isDel) {

        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        if (!msgType.equals(CHAT_MSG)) {
            map.put("id", id);
        }
        map.put("operation", isDel ? "del" : "read");
        map.put("msg_type", msgType);
        if (msgType.equals(CHAT_MSG)) {
            map.put("from_id", mData.get(position).getFrom_id());
        }
        this.isDel = isDel;
        mPresenter.updateMsgStatus(map);
    }

    @Override
    public void onUpdateMsgStatus(MsgNum data) {
        if (isDel) {
            mData.remove(removedPosition);
            mAdapter.notifyItemRemoved(removedPosition);
            mAdapter.notifyItemRangeChanged(removedPosition, mData.size());
        } else {
            mData.get(changedPosition).setIs_read(true);
            mAdapter.notifyItemChanged(changedPosition);
        }
        HashMap<String, Integer> map = new HashMap<>();
        map.put(ADMIN_MSG, data.getAdmin_num());
        map.put(ORDER_MSG, data.getOrder_num());
        map.put(CHAT_MSG, data.getChat_num());
        EventBus.getDefault().post(new BaseEvent<>(MSG_NUM, map));
        if (!isDel) {
            gotoOtherActivity();
        }

    }

    private void gotoOtherActivity() {
        switch (msgType) {
            case "order":
                RouterUtils.getInstance()
                        .build(RouterConstants.PATH_ORDER_DETAIl)
                        .withString(StringConstant.ID, msg.getRemark().getOrderId())
                        .navigation();
                break;
            case "chat":
                Intent intent = new Intent(mContext, ChatRoomActivity.class);
                intent.putExtra(URL, msg.getChat_url());
                mContext.startActivity(intent);
                break;
            case "admin":
                Intent intent1 = new Intent(mContext, MessageDetailActivity.class);
                intent1.putExtra(URL, msg.getContent());
                intent1.putExtra("title", msg.getTitle());
                mContext.startActivity(intent1);
                break;
        }
    }


    @Override
    protected void initData() {

    }


    @Override
    protected void onFirstUserVisible() {
        if (isFirst) {
            pageNo = 1;
            getData();
        }
    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        isFirst = false;
        pageNo = 1;
        getData();
    }

    private void getData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("page", pageNo);
        map.put("limit", LibConstant.PAGE_SIZ);
        mPresenter.getMsgList(map);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_msg_list;
    }


    @Override
    public void onGetMsgList(List<CommonList<Msg>> data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        HashMap<String, Integer> map = new HashMap<>();
        if (data == null || data.isEmpty()) {
            return;
        }
        CommonList<Msg> commonList = null;
        for (CommonList<Msg> item : data) {
            if (item.getType().equals(msgType)) {
                commonList = item;
            }
            map.put(item.getType(), item.getUnread_num());
        }
        if (commonList == null) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
            return;
        }
        if (pageNo == 1) {
            mData.clear();
        }
        mData.addAll(commonList.getList());
        if (commonList.getList().size() < LibConstant.PAGE_SIZ) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
        } else {
            isCanloadMore = true;
            refreshLayout.setEnableLoadMore(true);
        }
        if (!mData.isEmpty()) {
            showPageContent();
        } else {
            showPageEmpty();
        }
        mAdapter.notifyDataSetChanged();
        EventBus.getDefault().post(new BaseEvent<>(MSG_NUM, map));

    }

    @Override
    public void onGetMsgFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        showPageError();
    }

    int actualLe = 0;

    public int lengthOfLongestSubstring(String s) {
        if (TextUtils.isEmpty(s)) {
            return 0;
        }
        int length = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (!sb.toString().contains(s.substring(i, i + 1))) {
                sb.append(s.substring(i, i + 1));
                length = i + 1;
            } else {
                length = length < i ? i : length;
                lengthOfLongestSubstring(s.substring(1));
                break;
            }

        }
        actualLe = actualLe < length ? length : actualLe;
        return actualLe;
    }


}
